﻿using DatabaseServer.Server;
using ServerCommon.Architecture;
using ServerCommon.Log;
using ServerCommon.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseServer
{
    public class ProgramDatabaseServer : ProgramServer<ProgramDatabaseServer>
    {
        private static LogHelper log = LogHelper.GetLogger(typeof(ProgramDatabaseServer));

        public override int Init(ProgramServerType serverType, string appName, string configPath, long serverId = 0)
        {
            base.Init(serverType, appName, configPath, serverId);

            DatabaseNet.Instance.Init();

            UpdateStatus(ServerStatusType.Init);
            log.InfoFormat("DatabaseServer init serverId - {0}, server status - {1}", ServerId, ServerStatus);
            return 0;
        }

        public override void Run()
        {
            base.Run();
            UpdateStatus(ServerStatusType.Run);

            waitFor((frameCur) =>
            {
                try
                {
                    DatabaseNet.Instance.Run();
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                return true;
            },
                (frameCost) =>
                {
                    return true;
                }
            );

            UpdateStatus(ServerStatusType.Stop);

            DatabaseNet.Instance.Stop();

            Thread.Sleep(1000);
        }

        public override void Release()
        {
            try
            {
                base.Release();

                UpdateStatus(ServerStatusType.Release);

                DatabaseNet.Instance.Release();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
    }
}
